<html>
    <head>
        <script>
            var fetchFreq = 30000; // how often we fetch new tweets (30s)
            var req; // request object
            var unreadCount = 0; // how many unread tweets we have
            var tweets; // all unread tweets
            var unreadTweets = []; // all unread tweets id
 
            if (!localStorage.unreadTweets) 
                localStorage.unreadTweets = JSON.stringify(unreadTweets);
            else 
                unreadTweets = JSON.parse(localStorage.unreadTweets);
            
            getTweets();
            setInterval(getTweets, fetchFreq);
            
            // fetch timeline from server
            function getTweets(){
                req = new XMLHttpRequest();
                
                if (!(localStorage.searchTerm)) 
                    localStorage.searchTerm = '';
                
                
                if (localStorage.searchTerm != '') 
                    req.open('GET', 'http://search.twitter.com/search.json?q=' + localStorage.searchTerm + '&result_type=recent');
                else 
                    req.open('GET', 'http://twitter.com/statuses/public_timeline.json?result_type=recent');
                
                req.onload = processTweets;
                req.send();
            }
            
            // process new batch of tweets
            function processTweets(){
                var res = JSON.parse(req.responseText);
                var newTweets = new Array();
                
                if (localStorage.searchTerm != '') 
                    res = res.results;
                
                for (var i = res.length - 1; i >= 0; i--) {
                    if (unreadTweets[res[i].id] == undefined) {
                        if (tweets == undefined) {
                            tweets = new Array();
                        }
                        
						// add new elements at the beginning of the array							                        
                        tweets.unshift(res[i]);

                        unreadTweets[res[i].id] = "loaded";
                        unreadCount++;
                    }
                }
                                                
                localStorage.unreadTweets = JSON.stringify(unreadTweets);
                localStorage.tweets = JSON.stringify(tweets);
                
                if (unreadCount > 0) {
                    chrome.browserAction.setBadgeBackgroundColor({
                        color: [255, 0, 0, 255]
                    });
                    chrome.browserAction.setBadgeText({
                        text: '' + unreadCount
                    });
                }
            }
        </script>
    </head>
</html>
